package com.justnow.offer;

import java.util.ArrayList;
import java.util.Stack;
import java.util.regex.Pattern;

/**
 * @author justnow
 * Created on 2020-09-21
 * Description
 */
public class WuBa01 {
    public static void main(String[] args) {
        String input = "9 + 10 / 2";
        WuBa01 wuBa01 = new WuBa01();
        int calculate = wuBa01.calculate(input);
        System.out.println(calculate);
    }

    public int calculate (String input) {
        // write code here
        ArrayList<String> last = getLast(input);
        Stack<Integer> stack = new Stack<>();
        for (String s : last) {
            if (isInteger(s)) {
                stack.add(Integer.valueOf(s));
            }
            if (s.equals("*")) {
                Integer number1 = stack.pop();
                Integer number2 = stack.pop();
                stack.add(number2 * number1);
            }
            if (s.equals("/")) {
                Integer number1 = stack.pop();
                Integer number2 = stack.pop();
                stack.add(number2 / number1);
            }
            if (s.equals("+")) {
                Integer number1 = stack.pop();
                Integer number2 = stack.pop();
                stack.add(number2 + number1);
            }
            if (s.equals("-")) {
                Integer number1 = stack.pop();
                Integer number2 = stack.pop();
                stack.add(number2 - number1);
            }
        }
        return stack.get(0);

    }

    public ArrayList<String> getLast(String input) {
        ArrayList<String> res = new ArrayList<>();
        Stack<String> stack = new Stack<>();
        String[] str = input.split(" ");
        for (String s : str) {
            if (isInteger(s)) {
                res.add(s);
            }
            if (stack.isEmpty()) {
                stack.add(s);
            } else {
                if (s.equals("*") || s.equals("\\")) {
                    while (stack.peek().equals("*") || stack.peek().equals("*")) {
                        String pop = stack.pop();
                        res.add(pop);
                    }
                    res.add(s);
                } else {
                    while (!stack.isEmpty()) {
                        res.add(stack.pop());
                    }
                    res.add(s);
                }
            }

        }
        return res;

    }

    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

}
